<?php


namespace app\api\controller\xiluedu;


use app\common\controller\Api;
use app\common\model\xiluedu\Maxim AS MaximModel;
use app\common\model\xiluedu\UserFavourite;
use function fast\array_get;

class Maxim extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 每日一句
     */
    public function daily_sentence(){
        $row = MaximModel::with(['teacher'=>function($query){
            $query->withField(['id','name','job','thumb_image']);
        },
            'userFavorite'=>function($query){
                $query->withField(['id','favourite_type','favourite_id'])->where('favourite_type',UserFavourite::TYPE_MAXIM);
            }
            ])
            ->where('maxim.status',1)
            ->orderRaw('rand()')
            ->find();
        if(!$row) $this->success('', []);
        $row->fav_count = 0;
        if($this->auth->isLogin()){
            $row->fav_count = UserFavourite::isFav($this->auth->id,$row->id,UserFavourite::TYPE_MAXIM);
        }
        $this->success('查询成功',$row);
    }

    /**
     * 导师箴言列表
     */
    public function lists(){
        $params = $this->request->param('');
        $pagesize = array_get($params,'pagesize',10);
        $row = MaximModel::with(['teacher'=>function($query){
            $query->withField(['id','name','job']);
        },
            'userFavorite'=>function($query){
            $query->withField(['id','favourite_type','favourite_id'])->where('favourite_type',UserFavourite::TYPE_MAXIM);
        }])
            ->where('recom_status',1)
            ->where('status',1)

            ->order('updatetime','desc')
            ->paginate($pagesize);
        $this->success('查询成功',$row);
    }

    /**
     * @ApiTitile (点赞&取消点赞)
     * @ApiSummary (点赞&取消点赞)
     * @ApiMethod (POST)
     * @ApiRoute (/api/xiluedu.maxim/toggle_fav)
     * @ApiHeaders (name=token, type=string, require=true, description="Token")
     * @ApiParams (name=maxim_id, type=int, require=true, description="id")
     */
    public function toggle_fav() {
        $maxim_id = $this->request->post('maxim_id');
        $result = UserFavourite::toggleFav($this->auth->id, $maxim_id, UserFavourite::TYPE_MAXIM);
        $this->success('操作成功',['fav_count'=>$result]);
    }
}